package com.project.demo.util;

import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/common")
public class CommonUtils {

	private static final String UPLOAD_DIR = "C:/Users/50193/Desktop/";

	@PostMapping("/upload")
	public String handleFileUpload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "Please select a file to upload.";
		}
		try {
			byte[] bytes = file.getBytes();
			String uploadDir = UPLOAD_DIR;
			File uploadedFile = new File(uploadDir + file.getOriginalFilename());
			file.transferTo(uploadedFile);
			return file.getOriginalFilename();
		} catch (IOException e) {
			e.printStackTrace();
			return "File upload failed!";
		}
	}


	@GetMapping("/download/{fileName:.+}")
	@ResponseBody
	public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
		Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
		try {
			Resource resource = new UrlResource(filePath.toUri());
			if (resource.exists() || resource.isReadable()) {
				return ResponseEntity.ok()
						.contentType(MediaType.APPLICATION_OCTET_STREAM)
						.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
						.body(resource);
			} else {
				return ResponseEntity.notFound().build();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			return ResponseEntity.status(500).build();
		}
	}


}
